import type { MenuProps } from "antd"
import { Menu } from "antd"
// react-router 5
// import { useHistory } from "react-router-dom"
// react-router 6
import { useNavigate, useLocation, useMatches } from "react-router-dom"
import router from "@/routes/index"
import './Sidebar.scss'

type MenuItem = Required<MenuProps>["items"][number]
function getItem(
  label: React.ReactNode,
  key: React.Key,
  icon?: React.ReactNode,
  children?: MenuItem[],
  type?: "group"
): MenuItem {
  return {
    key,
    icon,
    children,
    label,
    type,
  } as MenuItem
}

// const items: MenuProps["items"] = [getItem("工作台", "home-dashboard", null)]
// const routes = router

const getRouterArr = (rlt: any[] = [], matches: any[] = [], routes: any): any[] => {
  if(!routes.children){
    return rlt
  }
  const curMatch = matches.shift()
  for(let i = 0; i < routes.children.length; i++){
    const routeItem = routes.children[i]
    if(routeItem.path === curMatch?.pathname){
      rlt.push(routeItem)
      return getRouterArr(rlt, matches, routeItem)
    }
  }
}

export default function Sidebar() {
  const navigate = useNavigate()
  const loc = useLocation()
  const matches = useMatches()
  const { routes } = router
  const routerLink = getRouterArr([], matches, { children: routes})

  const items: MenuProps["items"] = routerLink?.[1]?.children.map((item: any) => {
    return getItem(item?.handle?.title, item.path, item.icon)
  }) || []

  function handleClick(e: any) {
    // 路由跳转
    // navigate("/home/dashboard")
    navigate(e.key)
  }
  return (
    <div className="sidebar">
      <Menu
        className="sidebar-menu"
        onClick={ handleClick }
        style={{ width: 256 }}
        selectedKeys={[loc?.pathname]}
        defaultOpenKeys={["sub1"]}
        mode="inline"
        items={items}
      />
      <div className="collector">收起</div>
    </div>
  )
}
